﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace TAMSUP
{
    /// <summary>
    /// Interaction logic for LaporanPemakaianBarang.xaml
    /// </summary>
    public partial class LaporanPemakaianBarang : Window
    {
        private string ID1,ID2;
        private bool isUbah = false;
        private bool isSelected = false;
        private DataSet ubah = new DataSet();
        public LaporanPemakaianBarang()
        {
            InitializeComponent();
        }

        public LaporanPemakaianBarang(string ID1, string ID2)
        {
            this.ID1 = ID1;
            this.ID2 = ID2;
            isUbah = true;
            InitializeComponent();
            label1.Content = "Ubah Pemakaian";
            addButton.Content = "Edit";
            cancelButton.Content = "Cancel";
        }

        public LaporanPemakaianBarang(DataRowView row)
        {
            InitializeComponent();
            namaBox.Items.Add(row.Row.ItemArray.ElementAt(1).ToString());
            namaBox.SelectedIndex = 0;
            isSelected = true;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try {
                homeWindow.Con.Open();

                SqlDataAdapter da = new SqlDataAdapter("select nama_barang from Daftar_Barang", homeWindow.Con);
                DataSet ds = new DataSet();
                da.Fill(ds, "Daftar Barang");

                int count;

                if (!isSelected)
                {
                    count = ds.Tables["Daftar Barang"].Rows.Count + 1;

                    for (int i = 0; i < count - 1; i++)
                    {
                        namaBox.Items.Add(ds.Tables["Daftar Barang"].Rows[i].ItemArray.ElementAt(0).ToString());
                    }
                }

                tanggalDate.SelectedDate = DateTime.Now;

                if (isUbah)
                {
                    da = new SqlDataAdapter("select Nama_Barang,a.Tanggal,a.Jumlah,a.Keterangan,a.id_pemakaian from menggunakan as a inner join daftar_barang as b on a.ID_Barang = b.ID_Barang where b.Nama_Barang = '" + ID1 + "'", homeWindow.Con);
                    da.Fill(ubah, "Daftar Penggunaan");
                    namaBox.SelectedItem = ubah.Tables["Daftar Penggunaan"].Rows[0].ItemArray.ElementAt(0).ToString();
                    jumlahText.Text = ubah.Tables["Daftar Penggunaan"].Rows[0].ItemArray.ElementAt(2).ToString();
                    keteranganText.Text = ubah.Tables["Daftar Penggunaan"].Rows[0].ItemArray.ElementAt(3).ToString();
                    tanggalDate.Text = ubah.Tables["Daftar Penggunaan"].Rows[0].ItemArray.ElementAt(1).ToString();
                    namaBox.IsDropDownOpen = false;
                }

                homeWindow.Con.Close();
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
            }
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            if (errorChecking())
            {
                try {
                    homeWindow.Con.Open();

                    if (!isUbah)
                    {
                        string _Date1 = tanggalDate.SelectedDate.Value.ToString("M/d/yyyy");

                        SqlDataAdapter da = new SqlDataAdapter("select * from daftar_barang", homeWindow.Con);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "Daftar menggunakan");

                        int count = ds.Tables["Daftar menggunakan"].Rows.Count + 1;
                        string s = "";
                        int x = 0;
                        for (int i = 0; i < count - 1; i++)
                        {
                            if (namaBox.SelectedItem.ToString().Equals(ds.Tables["Daftar menggunakan"].Rows[i].ItemArray.ElementAt(1).ToString()))
                            {
                                s = ds.Tables["Daftar menggunakan"].Rows[i].ItemArray.ElementAt(0).ToString();
                                x = i;
                            }
                        }

                        int news = Int32.Parse(ds.Tables["Daftar menggunakan"].Rows[x].ItemArray.ElementAt(2).ToString()) - Int32.Parse(jumlahText.Text);

                        if (news >= 0)
                        {
                            string _Insert = @"insert into menggunakan (ID_barang, Tanggal, Jumlah, Keterangan)
                                      Values('" + s + "','" + _Date1 + "','" +
                                                     jumlahText.Text + "','" + keteranganText.Text + "')";

                            SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                            _cmd.ExecuteNonQuery();

                            _Insert = "update daftar_barang set total = " + news + " where ID_Barang = '" + s + "'";
                            _cmd = new SqlCommand(_Insert, homeWindow.Con);
                            _cmd.ExecuteNonQuery();
                            MessageBox.Show("Informasi pemakaian barang berhasil disimpan", "New Item Report");
                            homeWindow.Con.Close();
                            homeWindow.top.refresh();
                            restart();
                        }
                        else
                        {
                            MessageBox.Show("Jumlah barang sudah tidak mencukupi, stok : " + ds.Tables["Daftar menggunakan"].Rows[x].ItemArray.ElementAt(2).ToString(), "Error: Item Report");
                            jumlahText.Background = new SolidColorBrush(Color.FromRgb(255, 225, 0));
                            homeWindow.Con.Close();
                        }
                    }
                    else
                    {
                        string _Date1 = tanggalDate.SelectedDate.Value.ToString("M/d/yyyy");

                        SqlDataAdapter da = new SqlDataAdapter("select ID_barang,Total from daftar_barang where nama_barang = '" + namaBox.SelectedItem.ToString() + "'", homeWindow.Con);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "Daftar menggunakan");

                        int news = Int32.Parse(jumlahText.Text) - Int32.Parse(ubah.Tables["Daftar Penggunaan"].Rows[0].ItemArray.ElementAt(2).ToString());
                        news = Int32.Parse(ds.Tables["Daftar menggunakan"].Rows[0].ItemArray.ElementAt(1).ToString()) - news;

                        string _Insert = "update menggunakan set jumlah = '" + jumlahText.Text + "', tanggal = '" + DateTime.Now.Date.ToString("M/d/yyyy") + "', keterangan = '" + keteranganText.Text + "' where ID_pemakaian = '" + ubah.Tables["Daftar Penggunaan"].Rows[0].ItemArray.ElementAt(4).ToString() + "'";
                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();

                        _Insert = "update daftar_barang set total = " + news + " where ID_Barang = '" + ds.Tables["Daftar menggunakan"].Rows[0].ItemArray.ElementAt(0).ToString() + "'";
                        _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();
                        MessageBox.Show("Informasi pemakaian barang berhasil diubah", "Update Item Report");
                        homeWindow.Con.Close();
                        homeWindow.top.refresh();
                        homeWindow.top.Focus();
                        this.Close();
                    }
                }
                catch (SqlException sqle)
                {
                    MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                }
            }
        }

        private void restart()
        {
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            namaBox.SelectedIndex = -1;
            namaBox.Background = validColor;
            jumlahText.Text = "";
            jumlahText.Background = validColor;
            keteranganText.Text = "";
            keteranganText.Background = validColor;
            tanggalDate.SelectedDate = DateTime.Now;
            tanggalDate.Background = validColor;
        }

        private Boolean errorChecking()
        {
            Boolean valid = true;
            Brush invalidColor = new SolidColorBrush(Color.FromRgb(255, 225, 0));
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            int temp;
            if (namaBox.SelectedIndex == -1)
            {
                namaBox.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                namaBox.Background = validColor;
            }
            if ((jumlahText.Text == "") || (Int32.Parse(jumlahText.Text) < 1) || !Int32.TryParse(jumlahText.Text.ToString(), out temp))
            {
                jumlahText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                jumlahText.Background = validColor;
            }
            if (!valid)
            {
                MessageBox.Show("Ada kesalahan pengisian informasi pemakaian barang", "Invalid Information");
            }
            return valid;
        }


        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (isUbah)
            {
                homeWindow.top.refresh();
                homeWindow.top.Focus();
                this.Close();
            }
            else
            {
                restart();
            }
        }

        private void namaBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void pemakaianBarangWindow_Closed(object sender, EventArgs e)
        {
            homeWindow.top.refresh();
            homeWindow.top.Focus();
        }

        private string addNol(int x)
        {
            string temp = "";
            string angka = x.ToString();

            if (angka.Count() == 4)
            {
                temp = "0";
            }
            else if (angka.Count() == 3)
            {
                temp = "00";
            }
            else if (angka.Count() == 2)
            {
                temp = "000";
            }
            else if (angka.Count() == 1)
            {
                temp = "0000";
            }
            Console.WriteLine(temp);
            return temp;
        }

        private void tanggalDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
